<template>
  <view>
    <view class="time-div">
      <view class="time">{{ secondsFormat(time) }}</view>
    </view>
    <view class="task-div"> <span>+添加计时器</span> </view>
    <view class="btn-div">
      <view v-if="status != 3">
        <button class="btn" @click="status += 1">
          {{ btnName }}
        </button>
      </view>
      <view v-else class="sel-div">
        <button class="btn end" @click="status = 1">结束</button>
        <button class="btn keep" @click="status = 2">继续</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      btnName: "开始",
      time: 25 * 60,
      status: 1,
      timer: null,
    };
  },
  methods: {
    start() {
      if (!this.timer) {
        this.timer = setInterval(() => {
          if (this.time > 0) {
            this.time--;
          } else {
            this.stop();
          }
        }, 1000);
      }
    },
    stop() {
      clearInterval(this.timer);
      this.timer = null;
    },
    secondsFormat(sec) {
      let minute = Math.floor(sec / 60);
      let second = sec - minute * 60;

      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      return minute + ":" + second;
    },
  },
  watch: {
    status: {
      handler(val, oldval) {
        if (oldval == 3 && val == 1) {
          this.time = 25 * 60;
        }
        switch (val) {
          case 1:
            this.btnName = "开始";
            this.stop();
            break;
          case 2:
            this.btnName = "结束";
            this.start();
            break;
          default:
            this.stop();
        }
      },
    },
  },
};
</script>

<style lang='scss' scoped>
.time-div {
  width: 10rem;
  height: 10rem;
  align-items: center;
  margin: 0 auto;
  margin-top: 4rem;
  border: 2px solid #0ccb82;
  border-radius: 50%;
  .time {
    margin: 0 auto;
    line-height: 10rem;
    width: 5rem;
    font-size: 2rem;
  }
}
.task-div {
  width: 30vw;
  margin: 0 auto;
  margin-top: 2rem;
  span {
    color: #6b6161b3;
  }
}
.btn-div {
  margin-top: 3rem;
  .btn {
    width: 40vw;
    background-color: #0ccb82;
    color: #fff;
    border-radius: 120rpx;
  }

  .sel-div {
    margin-left: 3.2rem;
    .btn {
      float: left;
      margin-left: 2rem;
      width: 4rem;
      height: 4rem;
      line-height: 4rem;
      border-radius: 50%;
    }
    .keep {
      color: #6b6161b3;
      border: 1px solid #6b6161b3;
      background-color: #fff;
    }
    .end {
      color: red;
      border: 1px solid red;
      background-color: #fff;
    }
  }
}
</style>